<template>
  <div class="container">
    <navigate>编辑教育情况</navigate>
    <div class="title flex_row flex_align_center">
      <div class="bar"></div>
      <div class="text">当前教育情况</div>
    </div>
    <div class="card">
      <template v-for="(item, i) in education1">
        <van-cell-group
          v-if="item.opition_type == 1"
          class="nowrap input_outer father_relative"
        >
          <van-field
            readonly
            clickable
            v-model="item.val.name"
            :label="item.name"
            placeholder="请选择"
            @click="item.visible = true"
          />
          <v-picker
            :columns="item.templateOptions"
            valueKey="name"
            @confirm="
              item.val = $event;
              item.visible = false;
            "
            :isVisible="item.visible"
            @cancel="item.visible = false"
          />
          <img
            src="@/assets/images/common/right.png"
            class="right vertical_center"
            alt=""
          />
        </van-cell-group>

        <van-cell-group
          :key="i + '-++'"
          class="input_outer"
          v-else-if="item.opition_type == 2"
        >
          <van-field
            v-model="item.val"
            :label="item.name"
            placeholder="请输入"
          />
        </van-cell-group>
        <van-cell-group
          :key="i + '-'"
          class="input_outer father_relative"
          v-else
        >
          <van-field
            @click="item.visible = true"
            v-model="item.val"
            :label="item.name"
            placeholder="请选择"
          />
          <van-popup v-model="item.visible" round position="bottom">
            <van-datetime-picker
              class="date_time_picker"
              v-model="currentDate"
              type="year-month"
              title="选择年月"
              :min-date="minDate"
              @cancel="item.visible = false"
              @confirm="
                item.val = formatDate($event, 'yyyy年MM月');
                item.visible = false;
              "
              :max-date="maxDate"
              :formatter="formatter"
            />
          </van-popup>
          <img
            src="@/assets/images/common/right.png"
            class="right vertical_center"
            alt=""
          />
        </van-cell-group>
      </template>
    </div>
    <template v-for="(e, index) in education2">
      <div class="title flex_row flex_align_center">
        <div class="bar"></div>
        <div class="text">教育经历 {{ index + 1 }}</div>
        <div class="delete flex_align_center flex_row" @click="del(index)">
          <img src="@/assets/images/userRecord/delete.png" alt="" />
          删除
        </div>
      </div>
      <div class="card">
        <template v-for="(item, i) in e.list">
          <van-cell-group
            v-if="item.opition_type == 1"
            class="input_outer father_relative"
          >
            <van-field
              readonly
              clickable
              v-model="item.val.name"
              :label="item.name"
              placeholder="请选择"
              @click="item.visible = true"
            />
            <v-picker
              :columns="item.templateOptions"
              valueKey="name"
              @confirm="
                item.val = $event;
                item.visible = false;
              "
              :isVisible="item.visible"
              @cancel="item.visible = false"
            />
            <img
              src="@/assets/images/common/right.png"
              class="right vertical_center"
              alt=""
            />
          </van-cell-group>

          <van-cell-group
            :key="i + index + '-++'"
            class="input_outer"
            v-else-if="item.opition_type == 2"
          >
            <van-field
              v-model="item.val"
              :label="item.name"
              placeholder="请输入"
            />
          </van-cell-group>
          <van-cell-group
            :key="i + index + '-'"
            class="input_outer father_relative"
            v-else
          >
            <van-field
              @click="item.visible = true"
              v-model="item.val"
              :label="item.name"
              placeholder="请选择"
              readonly
            />
            <van-popup v-model="item.visible" round position="bottom">
              <van-datetime-picker
                class="date_time_picker"
                v-model="currentDate"
                type="year-month"
                title="选择年月"
                :min-date="minDate"
                @cancel="item.visible = false"
                @confirm="
                  item.val = formatDate($event, 'yyyy年MM月');
                  item.visible = false;
                "
                :max-date="maxDate"
                :formatter="formatter"
              />
            </van-popup>
            <img
              src="@/assets/images/common/right.png"
              class="right vertical_center"
              alt=""
            />
          </van-cell-group>
        </template>
      </div>
    </template>
    <button class="btn" @click="save">保存资料</button>
    <button @click="add" class="add flex_row flex_align_center">
      <img src="@/assets/images/userRecord/add.png" alt="" />
      添加教育经历
    </button>
  </div>
</template>

<script>
import {
  getTemplateList,
  submitSelfAssessment,
  queryArchivesResults,
} from "@/api/funcation/selfAssessment";
import { formatDate } from "@/utils/time";
import { getList, setList, getRememberList, init } from "../commonJS";
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState(["INFO"]),
  },
  data() {
    return {
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      education1: [], // 基础教育情况
      education2: [
        // 教育经历卡片（多条）
        { list: [] },
      ],
      userArchivesResults: [], // 接口返回的历史数据
    };
  },
  async created() {
    await this.getTemplate(); // 先加载模板结构
    await this.getArchivesResults(); // 再加载历史数据
  },
  methods: {
    async getArchivesResults() {
      const par = {
        user_id: this.INFO.id,
        type_id: 3,
      };
      const res = await queryArchivesResults(par);

      if (res.code === 200 && res.data[0]?.content) {
        try {
          // 解析接口数据（包含index字段）
          const records = JSON.parse(res.data[0].content);
          this.userArchivesResults = records;

          // 步骤1：根据记录中的index动态创建足够的教育经历卡片
          const maxIndex = records.reduce((max, item) => {
            // 取所有记录中最大的index（如第二条数据index为1）
            return Math.max(max, item.index ?? 0);
          }, 0);

          // 如果现有卡片数量不足，动态添加（确保至少有maxIndex + 1个卡片）
          while (this.education2.length <= maxIndex) {
            this.add(); // 调用add方法新增卡片
          }

          // 步骤2：按index匹配对应的教育经历卡片，回显数据
          records.forEach(({ questionId, answerId, index = 0 }) => {
            // 根据index定位到对应的教育经历卡片（如index=0对应第一个卡片）
            const targetCard = this.education2[index];
            if (!targetCard) return;

            // 在当前卡片中查找匹配的问题（按questionId）
            const targetItem = targetCard.list.find(
              (item) => Number(item.id) === Number(questionId)
            );
            if (!targetItem) return;

            // 根据问题类型回显答案
            if (targetItem.opition_type === 1) {
              // 下拉选择项：匹配包含id和name的选项对象
              const option = targetItem.templateOptions.find(
                (opt) => opt.id === answerId
              );
              if (option) this.$set(targetItem, "val", option);
            } else {
              // 输入框/日期：直接赋值
              this.$set(targetItem, "val", answerId);
            }
          });
        } catch (e) {
          console.error("解析或回显数据失败:", e);
        }
      }
    },
    async getArchivesResults() {
      const par = {
        user_id: this.INFO.id,
        type_id: 3,
      };
      const res = await queryArchivesResults(par);
      console.log("接口返回的原始数据:", res.data[0]?.content);

      if (res.code === 200 && res.data[0]?.content) {
        try {
          const records = JSON.parse(res.data[0].content);
          this.userArchivesResults = records;

          // --------------------------
          // 单独处理 education1（基础教育情况）
          // --------------------------
          records.forEach(({ questionId, answerId }) => {
            // 在 education1 中查找匹配的问题（无需考虑 index）
            const targetItem = this.education1.find(
              (item) => Number(item.id) === Number(questionId)
            );
            if (targetItem) {
              // 回显基础教育情况的答案
              if (targetItem.opition_type === 1) {
                const option = targetItem.templateOptions.find(
                  (opt) => opt.id === answerId
                );
                if (option) this.$set(targetItem, "val", option);
              } else {
                this.$set(targetItem, "val", answerId);
              }
            }
          });

          // --------------------------
          // 处理 education2（教育经历，按 index）
          // --------------------------
          const maxIndex = records.reduce((max, item) => {
            return Math.max(max, item.index ?? 0);
          }, 0);

          while (this.education2.length <= maxIndex) {
            this.add();
          }

          records.forEach(({ questionId, answerId, index = 0 }) => {
            const targetCard = this.education2[index];
            if (!targetCard) return;

            const targetItem = targetCard.list.find(
              (item) => Number(item.id) === Number(questionId)
            );
            if (!targetItem) return;

            if (targetItem.opition_type === 1) {
              const option = targetItem.templateOptions.find(
                (opt) => opt.id === answerId
              );
              if (option) this.$set(targetItem, "val", option);
            } else {
              this.$set(targetItem, "val", answerId);
            }
          });
        } catch (e) {
          console.error("解析或回显数据失败:", e);
        }
      }
    },

    async save() {
      // 1. 处理基础教育情况（education1）：无需index
      const education1Pairs = this.education1.map((item) => ({
        questionId: item.id,
        answerId: this.getAnswerValue(item),
      }));

      // 2. 处理教育经历（education2）：为每条记录添加index（对应卡片索引）
      const education2Pairs = this.education2.flatMap((card, index) => {
        // 遍历当前卡片（index为0表示第一条教育经历）的所有问题
        return card.list.map((item) => ({
          questionId: item.id,
          answerId: this.getAnswerValue(item),
          index: index, // 核心：添加index标识（第一条0，第二条1...）
        }));
      });

      // 合并所有数据并提交
      const allPairs = [...education1Pairs, ...education2Pairs];
      console.log("最终提交的数据（含index）:", allPairs);

      const par = {
        user_id: this.INFO.id,
        content: JSON.stringify(allPairs),
        type_id: 3,
        source: 1,
      };

      const r = await submitSelfAssessment(par);
      if (r.code === 200) {
        this.$toast.success("保存成功！");
      }
    },

    // 辅助方法：根据问题类型获取答案值（id或文本）
    getAnswerValue(item) {
      if (item.opition_type === 1) {
        // 下拉选择项：返回选项id
        return item.val?.id ?? item.val;
      } else {
        // 输入框/日期：直接返回值
        return item.val;
      }
    },

    // 加载模板结构（初始化表单字段）
    async getTemplate(callback) {
      const res = await getTemplateList({ id: "3" });
      if (res.code === 200) {
        this.education1 = res.data[0].templates[0].children; // 基础教育情况
        this.education2[0].list = res.data[0].templates[1].children; // 第一条教育经历
        // 初始化表单默认值
        init(this, this.education1);
        init(this, this.education2[0].list);
        callback && callback();
      }
    },

    // 新增教育经历卡片（点击"添加教育经历"时调用）
    add() {
      // 深拷贝最后一个卡片的结构（清空值）
      const lastCard = this.education2[this.education2.length - 1];
      if (!lastCard) return;

      const newList = lastCard.list.map((item) => {
        const copy = JSON.parse(JSON.stringify(item));
        copy.val = ""; // 清空输入值
        return copy;
      });

      // 添加新卡片（index为当前长度，如第二条卡片index=1）
      this.education2.push({ list: newList });
    },

    // 删除教育经历卡片（保留至少一条）
    del(index) {
      if (this.education2.length <= 1) {
        return this.$toast.fail("至少保留一条教育经历！");
      }
      this.education2.splice(index, 1);
    },

    formatDate,
    formatter(type, val) {
      if (type === "year") return `${val}年`;
      if (type === "month") return `${val}月`;
      return val;
    },
  },
};
</script>

<style lang="less" scoped>
@import "./css/index.less";
@import "../styles/common.less";
</style>
